using System;
using System.Collections;
using System.Collections.Generic;
using CinemaDirector;
using ProtoModels;
using UnityEngine;

public class MultiplayerLobbyLayer : UILayer, MatchEventsDelegate
{
	public enum GameType
	{
		Server = 0,
		Client = 1,
		FindMatch = 2
	}

	public enum RequestType
	{
		AskMatch = 0,
		IsWaiting = 1,
		Remove = 2
	}

	[Serializable]
	public class PlayerBoard
	{
		public Transform topTransform;

		public UISprite background;

		public Vector3 initialTopTransformPos;

		public Vector3 from;

		public Vector3 to;
	}

	[Serializable]
	public class MovableObject
	{
		public Transform topTransform;

		public Vector3 initialTopTransformPos;

		public Vector3 from;

		public Vector3 to;
	}

	protected struct MyState
	{
		public bool isHandShakeSent;

		public bool isHandShakeReceived;

		public bool isAskResponseReceived;

		public bool isServer;

		public int clientRetries;

		public bool clientPicketUpAddress;

		public float serverTimeoutTime;

		public float waitingPollTime;

		public bool isTesting;

		public string clientName;

		public bool createdRoom;

		public bool triedToJoinRoom;

		public bool isNetworkAvailable;

		public MatchParameters.MatchParams.MultiplayerParams p;

		public bool introAnimFinished;

		public float questionsTimer;

		public bool shownQuestions;

		public bool joinedLobby;

		public bool joinedRoomFailed;

		public bool joinedSqlLobby;

		public int skillLevel;
	}

	public FloatRange skillRange = new FloatRange
	{
		min = 0f,
		max = 3000f
	};

	public MovableObject lighting;

	public List<PlayerBoard> playerBoards = new List<PlayerBoard>();

	public UIPanel mainPanel;

	public Transform backButton;

	public UILabel vsLabel;

	public MovableObject vsLabelObject;

	public Vector3 vsLabelOffset;

	public float topPadding = 100f;

	public UIWidget bckShadow;

	private FloatRange bckShadowAlpha = new FloatRange
	{
		min = 0f,
		max = 0.8f
	};

	protected MultiplayerRoomType roomType;

	public UILabel playersLabel;

	public PlayerCareerStageDefinition.GameParameters gameParameters;

	public bool showTrivia = true;

	public TriviaController trivia;

	public Transform mainAnimPos;

	public Vector3 upAnimPos;

	public UILabel text;

	public UILabel wins;

	public UILabel titleLabel;

	public UILabel winPercent;

	public UILabel score;

	public new UILabel name;

	public UILabel level;

	public UISprite myFlag;

	public UITexture myAvatarTexture;

	private GGServerRequestsBackend.TextureRequest myTextureRequest;

	public UISprite opponentFlag;

	public UILabel opponentName;

	public UILabel opponentLevel;

	public CoinsController coinsController;

	public Cutscene introAnim;

	public Cutscene potAnim;

	public Cutscene freePotAnim;

	public UILabel fee;

	public UILabel win;

	public UISpinner spinner;

	public GameObject pot;

	public GameObject potLabel;

	protected float timeoutBetweenWaitingPoll = 2f;

	protected float serverTimeout = 10f;

	protected string supportRoomNameGUID;

	private float lobbyTimer;

	public LeaderboardPositionDisplay display1;

	public LeaderboardPositionDisplay display2;

	private MyState state;

	protected int maxClientRetries = 10;

	protected GameType gameType;

	protected StandardDeserializer deserializer = new StandardDeserializer();

	private float introTimeStamp;

	protected float countryTimer;

	public float countryChangeDuration = 0.25f;

	private int opponentFlagIndex;

	private MultiplayerRooms.RoomInfo info;

	private Coroutine moveMainTransformCoroutine;

	private bool isCutsceneFinished;

	private string pid = string.Empty;

	private Coroutine startTrainingCoroutine;

	private bool isConnected
	{
		get
		{
			return state.isHandShakeSent || GGNetwork.instance.ConnectedPlayers() > 0;
		}
	}

	public MultiplayerRooms.RoomInfo GetRoomInfo()
	{
		return MultiplayerRooms.instance.FindRoomByType(roomType);
	}

	public void FindMatch(MultiplayerRoomType type)
	{
		roomType = type;
		info = null;
		gameType = GameType.FindMatch;
		NavigationManager.instance.Push(base.gameObject);
	}

	public void FindMatch(MultiplayerRooms.RoomInfo info)
	{
		this.info = info;
		roomType = info.room;
		gameType = GameType.FindMatch;
		NavigationManager.instance.Push(base.gameObject);
	}

	private void Awake()
	{
		introTimeStamp = Time.timeSinceLevelLoad + UnityEngine.Random.Range(0f, 10f);
		deserializer.onIntro = OnIntro;
		foreach (PlayerBoard playerBoard in playerBoards)
		{
			playerBoard.initialTopTransformPos = playerBoard.topTransform.localPosition;
		}
		lighting.initialTopTransformPos = lighting.topTransform.localPosition;
		vsLabelObject.initialTopTransformPos = vsLabelObject.topTransform.localPosition;
		PhotonNetwork.CrcCheckEnabled = true;
	}

	private void ShowQuestions()
	{
		if (moveMainTransformCoroutine != null)
		{
			StopCoroutine(moveMainTransformCoroutine);
		}
		moveMainTransformCoroutine = StartCoroutine(DoMoveBoardsToTheSide(0.5f));
	}

	private void HideQuestions()
	{
		if (moveMainTransformCoroutine != null)
		{
			StopCoroutine(moveMainTransformCoroutine);
		}
		Debug.Log("HIDE QUESTIONS");
		moveMainTransformCoroutine = StartCoroutine(DoMoveBoardsToInitial(0.5f));
	}

	private IEnumerator DoMoveBoardsToTheSide(float duration)
	{
		foreach (PlayerBoard playerBoard in playerBoards)
		{
			Vector3 localPosition = playerBoard.topTransform.localPosition;
			Vector3 vector = new Vector3((!(playerBoard.initialTopTransformPos.x < 0f)) ? 10 : (-10), topPadding, 0f);
			Vector3[] worldCorners = mainPanel.worldCorners;
			int num = ((playerBoard.initialTopTransformPos.x < 0f) ? 1 : 2);
			Vector3 position = worldCorners[num];
			Transform parent = playerBoard.topTransform.parent;
			Vector3 position2 = playerBoard.background.worldCorners[num];
			Vector3 vector2 = parent.InverseTransformPoint(position);
			Vector3 vector3 = parent.InverseTransformPoint(position2);
			Vector3 vector4 = vector2 - vector3 - vector;
			Vector3 to = playerBoard.topTransform.localPosition + vector4;
			playerBoard.from = localPosition;
			to.y = playerBoard.initialTopTransformPos.y - vector.y;
			playerBoard.to = to;
		}
		PlayerBoard lightingBoard = playerBoards[1];
		Transform lParent = lighting.topTransform.parent;
		lighting.from = lighting.topTransform.localPosition;
		Vector3 lto = lParent.InverseTransformPoint(lightingBoard.topTransform.parent.TransformPoint(lightingBoard.to));
		lto.y = lighting.initialTopTransformPos.y;
		lighting.to = lto;
		float time = 0f;
		Vector3 mainAnimPosAtStart = mainAnimPos.localPosition;
		vsLabelObject.from = vsLabelObject.topTransform.localPosition;
		vsLabelObject.to = vsLabelObject.initialTopTransformPos + vsLabelOffset;
		UITools.ChangeText(text: "Warm Up for " + GetRoomInfo().roomName + " Match", label: vsLabel);
		UITools.SetActive(titleLabel, false);
		float bckAlphaAtStart = bckShadow.alpha;
		while (time < duration)
		{
			time += Time.deltaTime;
			float normTime = time / duration;
			foreach (PlayerBoard playerBoard2 in playerBoards)
			{
				playerBoard2.topTransform.localPosition = Vector3.Lerp(playerBoard2.from, playerBoard2.to, normTime);
			}
			mainAnimPos.localPosition = Vector3.Lerp(mainAnimPosAtStart, upAnimPos, normTime);
			lighting.topTransform.localPosition = Vector3.Lerp(lighting.from, lighting.to, normTime);
			vsLabelObject.topTransform.localPosition = Vector3.Lerp(vsLabelObject.from, vsLabelObject.to, normTime);
			bckShadow.alpha = Mathf.Lerp(bckAlphaAtStart, bckShadowAlpha.min, normTime);
			yield return null;
		}
		UITools.SetActive(lighting.topTransform, false);
		bckShadow.cachedGameObject.SetActive(false);
	}

	private IEnumerator DoMoveBoardsToInitial(float duration)
	{
		foreach (PlayerBoard playerBoard in playerBoards)
		{
			Vector3 localPosition = playerBoard.topTransform.localPosition;
			Vector3 initialTopTransformPos = playerBoard.initialTopTransformPos;
			playerBoard.from = localPosition;
			playerBoard.to = initialTopTransformPos;
		}
		Transform lParent = lighting.topTransform.parent;
		lighting.from = lParent.InverseTransformPoint(lighting.topTransform.position);
		Vector3 lto = lighting.initialTopTransformPos;
		lighting.to = lParent.InverseTransformPoint(lto);
		float time = 0f;
		Vector3 mainAnimPosAtStart = mainAnimPos.localPosition;
		UITools.ChangeText(vsLabel, "VS");
		MultiplayerRooms.RoomInfo roomInfo = GetRoomInfo();
		UITools.SetActive(titleLabel, true);
		vsLabelObject.from = vsLabelObject.topTransform.localPosition;
		vsLabelObject.to = vsLabelObject.initialTopTransformPos + vsLabelOffset;
		float bckAlphaAtStart = bckShadow.alpha;
		bckShadow.cachedGameObject.SetActive(true);
		UITools.SetActive(lighting.topTransform, true);
		while (time < duration)
		{
			time += Time.deltaTime;
			float normTime = time / duration;
			foreach (PlayerBoard playerBoard2 in playerBoards)
			{
				playerBoard2.topTransform.localPosition = Vector3.Lerp(playerBoard2.from, playerBoard2.to, normTime);
			}
			mainAnimPos.localPosition = Vector3.Lerp(mainAnimPosAtStart, Vector3.zero, normTime);
			lighting.topTransform.localPosition = Vector3.Lerp(lighting.from, lighting.to, normTime);
			vsLabelObject.topTransform.localPosition = Vector3.Lerp(vsLabelObject.from, vsLabelObject.to, normTime);
			bckShadow.alpha = Mathf.Lerp(bckAlphaAtStart, bckShadowAlpha.max, normTime);
			yield return null;
		}
	}

	private IEnumerator DoMoveMainTransform(float duration, Vector3 from, Vector3 to)
	{
		float time = 0f;
		Debug.Log(string.Concat("Move main transform ", from, " to ", to));
		while (time < duration)
		{
			time += Time.deltaTime;
			mainAnimPos.localPosition = Vector3.Lerp(from, to, time / duration);
			Debug.Log(string.Concat("Move local ", mainAnimPos.localPosition, " time ", time));
			yield return null;
		}
	}

	private void OnEnable()
	{
		BehaviourSingletonInit<LeaderboardPositionInfoManager>.instance.ClearPlayerCache();
		lobbyTimer = 0f;
		GGPlayerSettings instance = GGPlayerSettings.instance;
		if (instance.Model.version < 1)
		{
			instance.UpdateModel();
		}
		HideQuestions();
		UITools.SetActive(bckShadow, true);
		bckShadow.alpha = bckShadowAlpha.max;
		Screen.sleepTimeout = -1;
		Ads.instance.hideBanner(true);
		ShowGame();
		if (!GGSupportMenu.instance.isNetworkConnected())
		{
			TableTennisDialog.instance.ShowOk("No internet connection", "No internet connection! Please connect to the internet and try again.", "Ok", delegate
			{
				NavigationManager.instance.Pop();
				NavigationManager.instance.Pop();
			});
		}
		else
		{
			DoOnEnable();
		}
	}

	private void DoOnEnable()
	{
		pot.SetActive(false);
		TableTennisMainNavigation tableTennisMainNavigation = NavigationManager.instance as TableTennisMainNavigation;
		tableTennisMainNavigation.OnGameShown(false);
		UITools.SetActive(backButton, true);
		potLabel.SetActive(false);
		supportRoomNameGUID = RoomName() + Guid.NewGuid().ToString();
		isCutsceneFinished = false;
		GGSupportMenu instance = GGSupportMenu.instance;
		state = default(MyState);
		state.skillLevel = GGPlayerSettings.instance.GetLobbyEloRating();
		Debug.Log("Elo Rating " + state.skillLevel);
		if (!instance.isNetworkConnected())
		{
			state.isNetworkAvailable = false;
			text.text = "You need to be connected to a network...";
			return;
		}
		GGPlayerSettings instance2 = GGPlayerSettings.instance;
		if (BehaviourSingletonInit<FriendProfilesManager>.instance.myProfile != null)
		{
			UITools.ChangeText(name, GGFormat.ScoreNameFormat(BehaviourSingletonInit<FriendProfilesManager>.instance.PlayerName));
			if (myTextureRequest == null)
			{
				myAvatarTexture.gameObject.SetActive(false);
				myFlag.gameObject.SetActive(true);
				UITools.ChangeSprite(myFlag, GameConstants.Instance.CountryForFlag(instance2.Model.flag).spriteName);
				if (GGPlayerSettings.instance.useProfilePictureInMultiplayer && BehaviourSingletonInit<FriendProfilesManager>.instance.myProfile.pictureUrl != string.Empty)
				{
					myTextureRequest = new GGServerRequestsBackend.TextureRequest(BehaviourSingletonInit<FriendProfilesManager>.instance.myProfile.pictureUrl);
					myTextureRequest.cache = CacheStategy.CacheToFile;
					myTextureRequest.onComplete = OnMyTextureRequestComplete;
					BehaviourSingleton<GGRequestLimitter>.instance.Add(myTextureRequest);
				}
			}
		}
		else
		{
			UITools.ChangeText(name, GGFormat.ScoreNameFormat((!(instance2.GetName() != "Anonymous")) ? "You" : instance2.GetName()));
			UITools.ChangeSprite(myFlag, GameConstants.Instance.CountryForFlag(instance2.Model.flag).spriteName);
		}
		UITools.ChangeText(wins, "Wins: " + instance2.Model.multiplayerWins);
		string @string = ScriptableObjectSingleton<SettingsUI>.instance.GetString("Rating");
		UITools.ChangeText(score, @string + ": " + instance2.GetDisplayEloRating().ToString());
		UITools.ChangeText(opponentName, GGFormat.ScoreNameFormat("Searching..."));
		UITools.ChangeText(level, @string + ": " + GGPlayerSettings.instance.GetDisplayEloRating());
		UITools.SetActive(opponentLevel, false);
		UITools.ChangeText(opponentLevel, @string + ": ?");
		UITools.ChangeText(fee, GGFormat.FormatPrice(MultiplayerRooms.instance.FindRoomByType(roomType).fee));
		UITools.ChangeText(win, GGFormat.FormatWinnings(MultiplayerRooms.instance.FindRoomByType(roomType).prize));
		MultiplayerRooms.RoomInfo roomInfo = GetRoomInfo();
		UITools.ChangeText(titleLabel, roomInfo.roomName + " Match");
		foreach (PlayerBoard playerBoard in playerBoards)
		{
			playerBoard.topTransform.localPosition = playerBoard.initialTopTransformPos;
		}
		lighting.topTransform.localPosition = lighting.initialTopTransformPos;
		vsLabelObject.topTransform.localPosition = vsLabelObject.initialTopTransformPos;
		UITools.ChangeText(vsLabel, "VS");
		mainAnimPos.transform.localPosition = Vector3.zero;
		spinner.StartSpinning();
		potAnim.CutsceneFinished -= CutsceneHandler;
		potAnim.CutsceneFinished += CutsceneHandler;
		freePotAnim.CutsceneFinished -= CutsceneHandler;
		freePotAnim.CutsceneFinished += CutsceneHandler;
		introAnim.CutsceneFinished -= CutsceneHandler;
		introAnim.CutsceneFinished += CutsceneHandler;
		RestartServer(GGNetwork.ServerType.FastestServer);
		text.text = "Looking for a match...";
		Analytics.instance.ReportMultiplayerEvent("OpenLobby");
		potAnim.Stop();
		freePotAnim.Stop();
		introAnim.Stop();
		introAnim.Play();
		StopAllCoroutines();
		GGDebug.Log("Stop ALL COROUTINES");
		StartCoroutine(JoinRoomFilterFlow());
		StartCoroutine(BehaviourSingletonInit<GGServerRequestsBackend>.instance.GetPlayerId(delegate(GGServerRequestsBackend.ServerRequest request)
		{
			if (request.status == GGServerRequestsBackend.ServerRequest.RequestStatus.Success)
			{
				pid = request.GetResponse<Pid>().pid;
				display1.FetchPlayerInfo(pid);
			}
		}));
	}

	public void OnMyTextureRequestComplete(GGServerRequestsBackend.ServerRequest request)
	{
		GGServerRequestsBackend.TextureRequest textureRequest = request as GGServerRequestsBackend.TextureRequest;
		if (textureRequest != null && textureRequest == myTextureRequest)
		{
			if (request.status != 0)
			{
				myTextureRequest = null;
				return;
			}
			myAvatarTexture.gameObject.SetActive(true);
			myFlag.gameObject.SetActive(false);
			myAvatarTexture.mainTexture = textureRequest.response;
		}
	}

	private void RestartServer(GGNetwork.ServerType serverType)
	{
		GGNetwork instance = GGNetwork.instance;
		instance.StopServer();
		instance.onMessageReceived -= OnNetworkMessage;
		instance.onMessageReceived += OnNetworkMessage;
		state.joinedLobby = false;
		state.joinedSqlLobby = false;
		state.joinedRoomFailed = false;
		GameType gameType = this.gameType;
		if (gameType == GameType.FindMatch)
		{
			instance.StartToServer(ConfigBase.instance.GetMatchServerAppName(), serverType);
		}
	}

	private void OnDisable()
	{
		Debug.Log("Disable Lobby Layer");
		StopAllCoroutines();
		GGNetwork instance = GGNetwork.instance;
		instance.onMessageReceived -= OnNetworkMessage;
		potAnim.CutsceneFinished -= CutsceneHandler;
		freePotAnim.CutsceneFinished -= CutsceneHandler;
		introAnim.CutsceneFinished -= CutsceneHandler;
		Ads.instance.hideBanner(false);
		HideGame();
	}

	private void OnNetworkMessage(GGNetwork network)
	{
		Debug.Log("Message in lobby layer");
		if (!state.isHandShakeReceived)
		{
			network.PollMessage(deserializer);
		}
	}

	private void OnIntro(MIntro intro)
	{
		Debug.Log("OnIntro");
		if (state.isHandShakeReceived)
		{
			return;
		}
		Debug.Log("OnIntro");
		if (introTimeStamp == intro.timeStamp)
		{
			introTimeStamp = Time.timeSinceLevelLoad + UnityEngine.Random.Range(0f, 20f);
			Debug.Log("Resend Intro");
			SendIntro();
			return;
		}
		if (!state.isHandShakeSent)
		{
			Debug.Log("Send Hand shake");
			SendIntro();
		}
		if (MIntro.HasPlayerPosition(intro.version) && intro.playerPosition != null)
		{
			BehaviourSingletonInit<LeaderboardPositionInfoManager>.instance.AddPlayerPositionFromExternalSource(intro.playerPosition);
			display2.FetchPlayerInfo(intro.playerPosition.playerId);
		}
		else if (MIntro.HasPidInIntro(intro.version))
		{
			display2.FetchPlayerInfo(intro.opponentPid);
		}
		bool flag = introTimeStamp > intro.timeStamp;
		int num = ((!flag) ? 1 : 0);
		Debug.Log("myServerTag: " + num);
		MIntro mIntro = CreateIntro();
		MultiplayerRooms.RoomInfo roomInfo = MultiplayerRooms.instance.FindRoomByType(roomType);
		MIntro intro2 = mIntro;
		MatchParameters.MatchParams.ShoeParams shoeParams = default(MatchParameters.MatchParams.ShoeParams);
		shoeParams.moveSpeed = intro.remoteMoveSpeed;
		shoeParams.jumpSpeed = intro.remoteJumpSpeed;
		shoeParams.shotsToMinSpeed = intro.remoteShotsToMinSpeed;
		shoeParams.normalizedVisualSpeed = intro.normalizedVisualSpeed;
		shoeParams.shoesId = intro.shoeId;
		MatchParameters.MatchParams.ShoeParams remoteShoe = shoeParams;
		state.p = new MatchParameters.MatchParams.MultiplayerParams
		{
			opponentName = intro.myName,
			opponentFlag = intro.myFlag,
			activeTag = num,
			eloRank = intro.eloRank,
			multiplayerWins = intro.multiplayerWins,
			multiplayerLoses = intro.multiplayerLoses,
			roomType = roomType,
			opponentLevel = intro.level,
			opponentCoins = intro.opponentCoins,
			multiplayerVersion = intro.version,
			intro = intro2,
			supportRoomNameGUID = ((!flag) ? intro.supportRoomNameGUID : supportRoomNameGUID),
			racketId = intro.remoteRacketId,
			remoteShoe = remoteShoe,
			remoteLookGender = intro.remoteLookGender,
			remoteLooks = intro.remoteLooks,
			remoteSkills = new RemoteStats(intro.remoteSkills, remoteShoe.normalizedVisualSpeed, intro.remoteRacketId),
			useRoomParams = true,
			player2Pid = intro.opponentPid,
			opponentImageUrl = intro.opponentImageUrl,
			isRematch = false
		};
		state.isHandShakeReceived = true;
		Analytics.instance.ReportMultiplayerEvent("Matched");
		spinner.StopSpinWithSprite(intro.myFlag, intro.opponentImageUrl);
		UITools.ChangeText(opponentName, GGFormat.ScoreNameFormat(GetName(intro.myName)));
		string @string = ScriptableObjectSingleton<SettingsUI>.instance.GetString("Rating");
		UITools.ChangeText(opponentLevel, @string + ": " + GGPlayerSettings.instance.GetDisplayEloRating(intro.eloRank).ToString());
		if (state.introAnimFinished)
		{
			HideQuestions();
			StartPotAnim();
		}
	}

	private void StartPotAnim()
	{
		MultiplayerRooms.RoomInfo roomInfo = MultiplayerRooms.instance.FindRoomByType(roomType);
		Cutscene cutscene = ((roomInfo.fee > 0) ? potAnim : freePotAnim);
		potAnim.Stop();
		freePotAnim.Stop();
		cutscene.Play();
		if (startTrainingCoroutine != null)
		{
			StopCoroutine(startTrainingCoroutine);
		}
		UITools.SetActive(backButton, false);
		TableTennisMainNavigation tableTennisMainNavigation = NavigationManager.instance as TableTennisMainNavigation;
		tableTennisMainNavigation.OnGameShown(true);
	}

	private void CutsceneHandler(object sender, CutsceneEventArgs e)
	{
		Debug.Log("CutsceneHandler");
		if (sender == introAnim)
		{
			state.introAnimFinished = true;
			if (state.isHandShakeReceived)
			{
				StartPotAnim();
			}
			else
			{
				StartTrainingDelayed(3f);
			}
		}
		else if (sender == potAnim || sender == freePotAnim)
		{
			isCutsceneFinished = true;
		}
	}

	private string GetName(string name)
	{
		if (string.IsNullOrEmpty(name))
		{
			return "Opponent";
		}
		return name;
	}

	private void UpdateFlag()
	{
	}

	private string RoomName()
	{
		return ConfigBase.instance.GetMatchServerAppName() + roomType;
	}

	private void OnJoinedLobby()
	{
		if (!state.joinedSqlLobby)
		{
			state.joinedSqlLobby = true;
			TypedLobby typedLobby = new TypedLobby(RoomName(), LobbyType.SqlLobby);
			PhotonNetwork.JoinLobby(typedLobby);
			return;
		}
		state.joinedLobby = true;
		RoomInfo[] roomList = PhotonNetwork.GetRoomList();
		GGDebug.Log("ROOMS: " + roomList.Length);
		RoomInfo[] array = roomList;
		foreach (RoomInfo roomInfo in array)
		{
			object value = null;
			roomInfo.customProperties.TryGetValue("levelName", out value);
			string text = value as string;
			text = ((!string.IsNullOrEmpty(text)) ? text : "none");
			GGDebug.Log("R: " + roomInfo.name + " open " + roomInfo.open + " levelName " + text + " visible " + roomInfo.visible + " room " + roomInfo.playerCount);
		}
	}

	private void OnPhotonCreateRoomFailed()
	{
		Debug.Log("OnPhotonCreateRoomFailed");
		state.joinedRoomFailed = true;
		DoOnEnable();
	}

	private void OnPhotonMaxCccuReached()
	{
		Debug.Log("OnPhotonMaxCccuReached");
		DoOnEnable();
	}

	private void OnConnectionFail()
	{
		Debug.Log("OnConnectionFail");
		DoOnEnable();
	}

	private void OnFailedToConnectToPhoton()
	{
		Debug.Log("OnFailedToConnectToPhoton");
		DoOnEnable();
	}

	private void OnPhotonJoinRoomFailed()
	{
		Debug.Log("OnPhotonJoinRoomFailed");
		state.joinedRoomFailed = true;
	}

	private void OnPhotonRandomJoinFailed()
	{
		Debug.Log("OnPhotonRandomJoinFailed");
		state.joinedRoomFailed = true;
	}

	private IEnumerator WaitForJoinLobby()
	{
		while (!state.joinedLobby)
		{
			yield return null;
		}
	}

	private IEnumerator WaitForJoinRoomEnd()
	{
		while (!state.joinedRoomFailed && !state.isHandShakeSent)
		{
			yield return null;
		}
	}

	private IEnumerator JoinRoomFilterFlow()
	{
		int connectionTryIndex = 0;
		int currentConnectionRepeats = 0;
		RankedConnectionDescription.ConnectionDescription desc = ScriptableObjectSingleton<RankedConnectionDescription>.instance.GetDefault();
		while (true)
		{
			yield return StartCoroutine(WaitForJoinLobby());
			RankedConnectionDescription.ConnectionDescription.ConnectionTry connectionTry = desc.connectionTry[Mathf.Clamp(connectionTryIndex, 0, desc.connectionTry.Count - 1)];
			int numConnectTries = connectionTry.numConnectionTries;
			int tryIndex = 0;
			FloatRange filter = new FloatRange
			{
				min = state.skillLevel,
				max = state.skillLevel
			};
			do
			{
				if (tryIndex > 0)
				{
					yield return new WaitForSeconds(connectionTry.timeBetweenConnectTries);
				}
				float difference = Mathf.Lerp(0f, connectionTry.maxSkillLevelDifference, (float)tryIndex / (float)numConnectTries);
				filter.min = Mathf.Floor((float)state.skillLevel - difference);
				filter.max = Mathf.Ceil((float)state.skillLevel + difference);
				if (Mathf.Abs(filter.max - filter.min) < 2f)
				{
					filter.min -= 1f;
					filter.max += 1f;
				}
				string filterString = "C0 > " + Mathf.FloorToInt(filter.min) + " AND C0 < " + Mathf.CeilToInt(filter.max);
				Debug.Log("Filter String - " + filterString + " mySkill " + state.skillLevel);
				state.joinedRoomFailed = false;
				bool joinRandomSent = false;
				try
				{
					joinRandomSent = GGNetwork.instance.JoinRandomRoomWithFilter(RoomName(), filterString);
				}
				catch
				{
					Debug.Log("Exception at join random room with filter");
				}
				if (joinRandomSent)
				{
					Debug.Log("Waiting for join room end");
					yield return StartCoroutine(WaitForJoinRoomEnd());
					Debug.Log("Join room end");
				}
				else
				{
					Debug.Log("FALSE JoinRandomRoomWithFilter");
				}
				tryIndex++;
			}
			while (tryIndex <= numConnectTries && !isConnected);
			if (!isConnected)
			{
				GGDebug.Log("Create room skill " + state.skillLevel);
				GGNetwork.instance.CreateRoomForFilter(RoomName(), new object[1] { state.skillLevel });
				yield return new WaitForSeconds(connectionTry.waitInRoom.Random());
				if (isConnected)
				{
					break;
				}
				RestartServer(connectionTry.serverType);
				currentConnectionRepeats++;
				if (connectionTry.repeatTimes >= 0 && currentConnectionRepeats >= connectionTry.repeatTimes)
				{
					connectionTryIndex++;
					currentConnectionRepeats = 0;
				}
				continue;
			}
			break;
		}
	}

	private void ShowGame()
	{
		TableTennisMainNavigation tableTennisMainNavigation = NavigationManager.instance as TableTennisMainNavigation;
		tableTennisMainNavigation.characterView.ShowGame();
		TableTennisGameStartScript gameStartScript = tableTennisMainNavigation.gameStartScript;
		gameStartScript.ui.arrow.gameObject.SetActive(false);
		gameStartScript.ui.tabletopHighlight.HideHighlight();
		gameStartScript.DestroyInstantiatedGameObjects();
		MultiplayerRooms.RoomInfo roomInfo = GetRoomInfo();
		if (roomInfo != null)
		{
			ObjectLookCustomization arenaForName = ScriptableObjectSingleton<ArenaCustomizations>.instance.GetArenaForName(roomInfo.arenaName);
			if (arenaForName != null)
			{
				gameStartScript.arenaCustomizer.ApplyCustomization(arenaForName, null);
			}
		}
		tableTennisMainNavigation.SetHeader(TableTennisMainNavigation.HeaderType.None);
	}

	private void StartTraining()
	{
		if (!isConnected)
		{
			RealStartTraining();
		}
	}

	private void StartTrainingDelayed(float delay)
	{
		if (startTrainingCoroutine != null)
		{
			StopCoroutine(startTrainingCoroutine);
		}
		StartCoroutine(DoStartTrainingDelayed(delay));
	}

	private IEnumerator DoStartTrainingDelayed(float delay)
	{
		yield return new WaitForSeconds(delay);
		StartTraining();
	}

	private void RealStartTraining()
	{
		MultiplayerRooms.RoomInfo roomInfo = GetRoomInfo();
		TableTennisMainNavigation tableTennisMainNavigation = NavigationManager.instance as TableTennisMainNavigation;
		tableTennisMainNavigation.OnGameShown(true);
		TableTennisGameStartScript gameStartScript = tableTennisMainNavigation.gameStartScript;
		gameStartScript.DestroyInstantiatedGameObjects();
		MatchParameters.MatchParams matchParams = MatchParameters.MatchParams.CreateDefault();
		matchParams.arenaName = roomInfo.arenaName;
		matchParams.hitTargetsDefinition = gameParameters.hitTargetsDefinition;
		MatchParameters.InitParameters = matchParams;
		matchParams.eventsDelegate = this;
		TableTennisHitTargets tableTennisHitTargets = gameStartScript.CreateGameObject<TableTennisHitTargets>();
		gameStartScript.StartMatch(MatchType.SinglePlayer, tableTennisHitTargets);
		ShowQuestions();
	}

	public void StartMatch(TableTennisMatchController match)
	{
	}

	public void MatchComplete(TableTennisMatchController match)
	{
		StartTraining();
	}

	private void HideGame()
	{
		TableTennisMainNavigation tableTennisMainNavigation = NavigationManager.instance as TableTennisMainNavigation;
		if (tableTennisMainNavigation != null)
		{
			TableTennisGameStartScript gameStartScript = tableTennisMainNavigation.gameStartScript;
			gameStartScript.DestroyInstantiatedGameObjects();
			tableTennisMainNavigation.characterView.HideGame();
			tableTennisMainNavigation.OnGameShown(false);
		}
		if (MenuParameters.InitParameters.showTrainingTutorial)
		{
			tableTennisMainNavigation.trainingTutorial.AdvanceTutorial();
		}
	}

	private new void Update()
	{
		lobbyTimer += Time.deltaTime;
		if (NavigationManager.instance.shouldGoBack && !isConnected)
		{
			OnBack();
			return;
		}
		if (state.isNetworkAvailable)
		{
			if (GGSupportMenu.instance.isNetworkConnected())
			{
				DoOnEnable();
			}
			return;
		}
		if (pid != string.Empty && isCutsceneFinished)
		{
			isCutsceneFinished = false;
			Debug.Log("start multiplayer " + pid);
			state.p.player1Pid = pid;
			BehaviourSingleton<ScreenNavigation>.instance.LoadMultiplayerMatch(state.p, MultiplayerRooms.instance.FindRoomByType(roomType));
			Analytics.instance.ReportMultiplayerLobbyMatchFound(roomType.ToString(), lobbyTimer);
			Analytics.instance.ReportLobbyComplete(true, roomType.ToString());
		}
		UpdateFlag();
		GGNetwork instance = GGNetwork.instance;
		if (instance.isInError())
		{
			text.text = "Error with the connection, retry later...";
			DoOnEnable();
			return;
		}
		if (instance.ConnectedPlayers() <= 0 && state.isHandShakeSent)
		{
			DoOnEnable();
		}
		if (state.isHandShakeReceived)
		{
			if (instance.ConnectedPlayers() <= 0)
			{
				DoOnEnable();
			}
			return;
		}
		if (instance.ConnectedPlayers() > 0 && !state.isHandShakeSent)
		{
			text.text = "Found an opponent!";
			SendIntro();
			Debug.Log("opponent");
		}
		instance.PollMessage(deserializer);
	}

	private MIntro CreateIntro()
	{
		StoreItemsConfig.StoreItem usedItem = StoreItemsConfig.instance.GetUsedItem(StoreItemsConfig.StoreItem.ItemType.Shoe);
		StoreItemsConfig.StoreItem usedItem2 = StoreItemsConfig.instance.GetUsedItem(StoreItemsConfig.StoreItem.ItemType.Racket);
		int opponentCoins = GGPlayerSettings.instance.walletManager.CurrencyCount(MultiplayerRooms.instance.multiplayerCurrencyType);
		string playerName = BehaviourSingletonInit<FriendProfilesManager>.instance.PlayerName;
		PlayerStats playerStats = GGPlayerSettings.instance.statsManager.playerStats;
		MIntro mIntro = default(MIntro);
		mIntro.version = 4;
		mIntro.timeStamp = introTimeStamp;
		mIntro.myName = playerName;
		mIntro.myFlag = GGPlayerSettings.instance.Model.flag;
		mIntro.eloRank = GGPlayerSettings.instance.GetDisplayEloRatingInt();
		mIntro.multiplayerWins = GGPlayerSettings.instance.Model.multiplayerWins;
		mIntro.multiplayerLoses = GGPlayerSettings.instance.Model.multiplayerLoses;
		mIntro.level = GGPlayerSettings.instance.GetDisplayEloRatingInt();
		mIntro.opponentCoins = opponentCoins;
		mIntro.supportRoomNameGUID = supportRoomNameGUID;
		mIntro.remoteMoveSpeed = usedItem.moveSpeed;
		mIntro.remoteJumpSpeed = usedItem.jumpSpeed;
		mIntro.remoteShotsToMinSpeed = usedItem.shotsToMinSpeed;
		mIntro.normalizedVisualSpeed = usedItem.NormalizedVisualSpeed();
		mIntro.remoteRacketId = usedItem2.id;
		mIntro.remoteLookGender = GGPlayerSettings.instance.Model.genderSelect;
		mIntro.remoteLooks = ((GGPlayerSettings.instance.Model.look == null) ? new List<CharacterLookProperty>() : GGPlayerSettings.instance.Model.look);
		mIntro.remoteSkills = playerStats.GetOriginalSkillsList();
		mIntro.opponentImageUrl = ((!GGPlayerSettings.instance.useProfilePictureInMultiplayer || BehaviourSingletonInit<FriendProfilesManager>.instance.myProfile == null) ? string.Empty : BehaviourSingletonInit<FriendProfilesManager>.instance.myProfile.pictureUrl);
		mIntro.shoeId = usedItem.id;
		MIntro result = mIntro;
		MultiplayerRooms.RoomInfo room = MultiplayerRooms.instance.FindRoomByType(roomType);
		result.SetRoom(room);
		return result;
	}

	private void SendIntro()
	{
		GGNetwork network = GGNetwork.instance;
		state.isHandShakeSent = true;
		MIntro intro = CreateIntro();
		if (pid != string.Empty)
		{
			DoSendIntro(intro, network);
			return;
		}
		StartCoroutine(BehaviourSingletonInit<GGServerRequestsBackend>.instance.GetPlayerId(delegate(GGServerRequestsBackend.ServerRequest request)
		{
			if (request.status == GGServerRequestsBackend.ServerRequest.RequestStatus.Success)
			{
				pid = request.GetResponse<Pid>().pid;
				DoSendIntro(intro, network);
			}
			else
			{
				TableTennisDialog.instance.ShowOk("No server connection", "Couldn't connect to the server", "Ok", delegate
				{
					NavigationManager.instance.Pop();
					NavigationManager.instance.Pop();
				});
			}
		}));
	}

	private void DoSendIntro(MIntro intro, GGNetwork network)
	{
		intro.opponentPid = pid;
		intro.playerPosition = display1.myPosition;
		intro.Send(network);
	}

	public void OnBack()
	{
		GGNetwork.instance.StopServer();
		NavigationManager.instance.Pop();
		Analytics.instance.ReportMultiplayerLobbyQuit(roomType.ToString(), lobbyTimer);
		Analytics.instance.ReportLobbyComplete(false, roomType.ToString());
	}

	private void OnApplicationPause(bool paused)
	{
		OnBack();
	}
}
